/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        int n = 0;
        ListNode len = head;
        while (len != null) {
            n++;
            len = len.next;
        }
        // 要反转x组
        int x = n / k;
        ListNode cur = head;
        ListNode newHead = new ListNode();
        ListNode prev = newHead;
        for (int i = 0; i < x; i++) {
             // 头插法
            ListNode tmp = cur;
            for (int j = 0; j < k; j++) {
                ListNode next = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = next;
            }
            prev = tmp;
        }
        prev.next = cur;
        return newHead.next;
    }
}